package com.huawei.hgip.paintgame.m.data;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;

import com.huawei.hgip.paintgame.activity.HistoryActivity;
import com.huawei.hgip.paintgame.adapter.HistoryInfo;
import com.huawei.hgip.paintgame.util.PGUtil;

public class UserProfile  {
	
	public static int userId = 0;
	public static String sourceUri = null;
	//public static String result1Uri = null;
	public static String result2Uri = null;
	/*Socket*/
	private Socket socket = null;
	private static UserLog userLog = new UserLog();
	static SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss"); 
	static String dateString =null;
	
	//first login
	public void userRegister (String imei ,String model ) throws UnknownHostException, IOException,SocketException{
		
		//组织数据格式通过Socket接口发送给服务器
		//long imeiLong = Long.parseLong(imei);
		//System.out.println("TestStep 004:\n"+"userRegister,get userID from Server."+"\n 004 end.");
		//等待服务器返回userId,修改默认userId值
		try {
		socket = PGUtil.getSocket(PGUtil.BC_USER_REGISTER);
		DataOutputStream registOutputStr = new DataOutputStream(
				socket.getOutputStream());
		//System.out.println("TestStep Socket 006 :\n"+imeiLong+","+model+"\n  Socket 006 end.");
		//registOutputStr.write(longToByte(imeiLong));
		PGUtil.writeStringWithLength(imei, registOutputStr);
		PGUtil.writeStringWithLength(model, registOutputStr);
		
		registOutputStr.flush();
		
		InputStream registApplyIps = socket.getInputStream();

		int cResult = PGUtil.readInteger(registApplyIps);
		//System.out.println("TestStep regist 02 :\n"+cResult+"\n  regist 02 end.");
		if (PGUtil.BC_SYS_SUCCESS == cResult){
			userId = PGUtil.readInteger(registApplyIps);
			System.out.println("TestStep regist :\n"+userId+"\n  regist end.");
		} else{
			System.out.println("TestStep regist Failed! :\n");
		}

		registApplyIps.close();
		socket.close();
		}catch (IOException ex){
			throw new SocketException();
		}
		
		//在cfCard创建文件用于保存用户使用记录，文件名log.log
		//System.out.println("TestStep 005:\n"+"userRegister succsee userId = "+ userId +"!"+"\n 005 end.");
		try {
			if (true == userLog.createLogFile()) {
				System.out.println("TestStep :\n"+"logFile creat success!"+"\n 008 end.");
			}else {
				System.out.println("TestStep :\n"+"logFile creat failed!"+"\n 009 end.");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//写入日志
		String logForWrite =String.valueOf(PGUtil.BC_USER_REGISTER);
		Date curDate = new Date(System.currentTimeMillis());//获取当前时间 
		dateString = formatter.format(curDate); 
		logForWrite += ";"+userId;
		logForWrite += ";"+dateString+"\n";
		//记录本地数据 
		if (true==userLog.writeUserLog(logForWrite)) {
			System.out.println("TestStep :\n"+"regist Log success!"+"\n  end.");
		}else {
			System.out.println("TestStep :\n"+"regist Log failed!"+"\n  end.");
		}
		
	}
	//login
	public boolean userLogin () throws UnknownHostException, IOException,SocketException {
		//通过检查cdCard上是否有该userId的文件来判断是否为首次登录
		//如果文件存在 userExist = 1， 并以文件名修改userId的值
		System.out.println("TestStep :\n"+"userLogin"+"\n  end.");
		//组织数据格式通过Socket接口发送给服务器 进行用户登录
		//以免日志文件被误删，登录时检查。
		userLog.createLogFile();
		//业务类型修改为登录类型10200
		System.out.println("TestStep :\n"+"send login to server!"+"\n  end.");
		try{
		socket = PGUtil.getSocket(PGUtil.BC_USER_LOGIN);
		InputStream loginApplyIps = socket.getInputStream();
		int cResult = PGUtil.readInteger(loginApplyIps);
		System.out.println("TestStep Login  :\n"+cResult+"\n  Login  end.");
		if (PGUtil.BC_SYS_SUCCESS == cResult){
			//登录成功
			System.out.println("TestStep :\n"+"login to server success!"+"\n  end.");
			//解析登录返回值内容
	  		byte[] loginApplyByte = new byte[1];
	  		loginApplyIps.read(loginApplyByte);
	  		int msgNum = loginApplyByte[0]&0xff;
			System.out.println("TestStep :\n"+"get login message from server(num of msg):"+msgNum+"\n  end.");
		} else{
			//登录失败
			System.out.println("TestStep :\n"+"login to server failed!"+"\n  end.");
			loginApplyIps.close();
			socket.close();
			return false;
		}		
		
		loginApplyIps.close();
		socket.close();
		}catch (IOException ex){
			throw new SocketException();
		}
		
		//写入用户日志
		String logForWrite = String.valueOf(PGUtil.BC_USER_LOGIN);
		Date curDate = new Date(System.currentTimeMillis());//获取当前时间 
		dateString = formatter.format(curDate); 
		logForWrite += ";"+userId;
		logForWrite += ";"+dateString+"\n";
		//写入失败异常处理
		if (true==userLog.writeUserLog(logForWrite)) {
			System.out.println("TestStep :\n"+"login Log success!"+"\n end.");
		}else {
			System.out.println("TestStep :\n"+"login Log failed!"+"\n end.");
		}
		return true;
	}
	//写入使用记录
	public static void userRecord() throws IOException{
		//在一次搜索完成后记录 搜索源 结果 时间  业务类型 等信息
		//按日志格式写入
		String logForWrite = null;
		Date curDate = new Date(System.currentTimeMillis());//获取当前时间 
		dateString = formatter.format(curDate); 
		logForWrite = dateString;
		logForWrite += ";"+sourceUri;
		logForWrite += ";"+result2Uri+"\n";
		//logForWrite += ";"+result2Uri+"\n";
		
		if (true==userLog.writeUserLog(logForWrite)) {
			System.out.println("TestStep :\n"+"hsitory Log success!"+"\n  end.");
		}else {
			System.out.println("TestStep :\n"+"hsitory Log failed!"+"\n  end.");
		}
	}
	//读取日志 
	public static ArrayList<HashMap<String, String>> getLog() throws IOException{
		String[] logResult = null;
		// 从数据文件中 读取数据并 以列表形式输出
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		list.clear();
		/*
		HashMap<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("data", "日期/源图/结果");
		list.add(itemMap);
		*/
		logResult = userLog.readUserLog();
		for (int i = 0; i < logResult.length; i++) {
			String temp[] = new String[3];
			temp = logResult[i].split(";");
			//for (int j = 0; j < temp.length; j++) {
			//	System.out.println("temp"+j+":"+temp[j]+"\n  end.");
			//}
			if (14==temp[0].length()) {
				//System.out.println("temp  added.");
				HashMap<String, String> member = new HashMap<String, String>();
				//String imageUrlSource = temp[1];
				//String imageUrlResult = temp[2];
				member.put("data", temp[0]);
				member.put("source", temp[1]);
				member.put("result", temp[2]);
				list.add(member);
			}
		}
		return list;
	}
	
	// 获取历史记录信息
    public static ArrayList<HistoryInfo> getHistoryInfos() throws IOException {
        ArrayList<HistoryInfo> res = new ArrayList<HistoryInfo>();
        res.clear();
		//读取日志并添
        String[] logResult = null;
		/*
		HashMap<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("data", "日期/源图/结果");
		list.add(itemMap);
		*/
		logResult = userLog.readUserLog();
		for (int i = 0; i < logResult.length; i++) {
			String temp[] = new String[3];
			temp = logResult[i].split(";");
			if (19==temp[0].length()) {
	            HistoryInfo newInfo = new HistoryInfo();
	            //newInfo.data = temp[0].substring(0,temp[0].length()-2);
	            newInfo.data = temp[0];
	            newInfo.sourceUri = temp[1];
	            newInfo.resultUri = temp[2];
	            Bitmap source = BitmapFactory.decodeFile(temp[1]);
	            Bitmap result = BitmapFactory.decodeFile(temp[2]);
	            newInfo.source = source; 
	            newInfo.result = result;
	            res.add(newInfo);
			}
		}	
        return res;
    }
	
	
	
	//退出
	public void userQuit() throws UnknownHostException, IOException{
		
		socket = PGUtil.getSocket(PGUtil.BC_USER_LOGOUT);
		
		String logForWrite = String.valueOf(PGUtil.BC_USER_LOGOUT);
		Date curDate = new Date(System.currentTimeMillis());//获取当前时间 
		dateString = formatter.format(curDate); 
		logForWrite += ";"+userId;
		logForWrite += ";"+dateString+"\n";
		//记录本地数据 
		if (true==userLog.writeUserLog(logForWrite)) {
			System.out.println("TestStep :\n"+"logout Log success!"+"\n  end.");
		}else {
			System.out.println("TestStep :\n"+"logout Log failed!"+"\n  end.");
		}
		
	}
	//quit
	
	  public static byte[] longToByte(long number) {
	        long temp = number;
	        byte[] b = new byte[8];
	        for (int i = 0; i < b.length; i++) {
	            b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位
	            temp = temp >> 8; // 向右移8位
	        }
	        return b;
	    }

}
